package com.freight.order.serviceimpl;

import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.core.service.UserService;
import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.msg.utils.MyJPushClient;
import com.freight.order.dao.*;
import com.freight.order.dto.DocumentaryDto;
import com.freight.order.dto.EntrustDriverDto;
import com.freight.order.entity.*;
import com.freight.order.service.PcOrderEntrustedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
@Transactional
public class PcOrderEntrustedServiceImpl implements PcOrderEntrustedService {


    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private OrderOrderDao orderOrderDao;

    @Autowired
    private UserService userService;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private DocumentaryDao documentaryDao;

    @Autowired
    private OrderExtendDao orderExtendDao;

    @Autowired
    private OrderGoodsDao orderGoodsDao;


    @Override
    public void dispatchOrder(EntrustDriverDto entrustDriverDto) {

        User u = securityUtil.getCurrUser();
        User user =userService.get(Long.valueOf(entrustDriverDto.getUserIds()));
        if (!u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            throw new FreightException("账号无权限进行此操作");
        }

        OrderGoods orderGoods=orderGoodsDao.getOne(entrustDriverDto.getGoodsId());
        String [] userIdArray=entrustDriverDto.getUserIds().split(",");

        //判断订单剩余重量和司机承运重量
        if (entrustDriverDto.getGoodWeight() !=null && orderGoods.getGoodWeight()<(entrustDriverDto.getGoodWeight()*userIdArray.length)){
            throw new FreightException("剩余货物重量不足");
        }

        if(orderGoods.getStatus() != 3){
            throw new FreightException("货源已完结");
        }

        MyJPushClient jPushUtil = new MyJPushClient();

        for (int i=0;i<userIdArray.length;i++){
            Long userId= Long.valueOf(userIdArray[i]);

            OrderOrder orderOrder = new OrderOrder();
            ObjectUtil.copyPropertiesIgnoreNull(orderGoods,orderOrder);
            ObjectUtil.autoFillEqFieldsWithArgs(entrustDriverDto,orderOrder);

            orderGoods.setGoodWeight(orderGoods.getGoodWeight()-entrustDriverDto.getGoodWeight());

            if(orderGoods.getGoodWeight()==0){
                orderGoods.setStatus(5);
            }
            orderGoodsDao.save(orderGoods);

            orderOrder.setGoodsId(orderGoods.getId());
            orderOrder.setCompanyUserId(orderGoods.getCompanyUserId());
            orderOrder.setOrderState(0);
            orderOrder.setOrderStateDesc("待司机接单");


            orderOrder.setOrderSource("2");
            orderOrder.setId(null);
            orderOrder=orderOrderDao.save(orderOrder);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
            Date date= null;
            try {
                date = simpleDateFormat.parse(entrustDriverDto.getLoadingTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            OrderExtend orderExtend = new OrderExtend();
            orderExtend.setEstimateLoadingTime(date);
            orderExtend.setEstimateDischargeTime(cal.getTime());
            orderExtend.setOrderId(orderOrder.getId());

            orderExtendDao.save(orderExtend);

            String notificationTitle = "运单消息";
            String msgTitle = "运单消息";
            String msgContent = "平台向您派送一条运单，请及时查看。";
            List<String> aliasList = Arrays.asList(user.getUsername());
            jPushUtil.sendToAliasList( aliasList,notificationTitle, msgTitle, msgContent, "5",null,null,orderOrder.getId(),0);

            Message message = new Message();
            message.setTitle("运单消息");
            String content="平台向您派送一条运单，请及时查看。";
            message.setType("2");
            message.setTopicId("5");
            message.setContent(content);
            message.setUserId(userId);
            message=messageService.save(message);

            MessageSend messageSend=new MessageSend();
            messageSend.setUserId(userId);
            messageSend.setMessageId(message.getId());
            messageSend.setType("3");
            messageSendService.save(messageSend);

            //操作记录
            operationLogService.saveOperationLog(6,"平台派单给实际承运人",orderOrder.getId().toString());
        }
    }

}
